package top.lshaci.learning.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;

import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
import static io.netty.util.CharsetUtil.UTF_8;

/**
 * HttpServerHandlerTest
 *
 * <pre>
 *     HttpObject: 客户端和服务端相互通讯的数据被封装成HttpObject
 * </pre>
 *
 * @author lshaci
 * @since 1.0.0
 */
@Slf4j
public class HttpServerHandlerTest extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        // 判断 msg 是不是 HttpRequest请求
        if (msg instanceof HttpRequest) {
            log.debug("msg 类型: {}", msg.getClass());
            log.debug("客户端地址: {}", ctx.channel().remoteAddress());

            HttpRequest request = (HttpRequest) msg;
            String uri = request.uri();
            log.debug("URI: {}", uri);
            if ("/favicon.ico".equals(request.uri())) {
                log.debug("请求的是网站图标");
                DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
                ctx.writeAndFlush(response);
                return;
            }
            // 回复信息给浏览器 [http协议]
            ByteBuf buf = Unpooled.copiedBuffer("Hello, 我是服务器", UTF_8);
            // 构造一个Http Response
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buf);
            HttpHeaders headers = response.headers();
            headers.set(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=utf-8");
            headers.set(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());

            ctx.writeAndFlush(response);
        }
    }
}
